package com.example.administrator.hellowork;

import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.util.Log;


public class MainActivity extends AppCompatActivity {
private TextView textView;
private ImageView imageView;
private Button btnNext;
private int[] Boyimgs={
        R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5
};
private int index=0;
    private Handler handler;
    private final int MSG_CHANGE_Boyimgs = 1001;

    //是否处于暂停状态
    private boolean isPause = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=findViewById(R.id.text1);
        imageView=findViewById(R.id.img);
        btnNext=findViewById(R.id.btnNext);
        //new 快捷键 ctrl+shift+空格
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what ==MSG_CHANGE_Boyimgs){
                    index=(index+1)%Boyimgs.length;
                    imageView.setImageResource(Boyimgs[index]);
                    return true;
                }
                return false;
            }
        });

        btnNext.setOnClickListener(
                new View.OnClickListener() {
                    //快捷键 alt+enter
                    @Override
                    public void onClick(View v) {
                        isPause=!isPause;
                        //自动换图片
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                while (true){
                                    try{
                                        Thread.sleep(2000);
                                    }catch (InterruptedException e){
                                        e.printStackTrace();
                                    }
                                    //在子线程中不可以修改主线程创建的view
                                    //需要实用消息机制 告诉主线程更新
                                    if(!isPause) {
                                        Message message = new Message();
                                        message.what = MSG_CHANGE_Boyimgs;
                                        handler.sendMessage(message);
                                        Log.e("MainActivity", "send change message");
                                    }

                                }
                            }
                        }).start();

                    }

                });

    }


}
